<template>
  <div class="content-height scroll-bar">
    <div class="search-class">
      <Row>
        <Col span="24">
        <Button
          type="primary"
          style="margin-right: 15px"
          v-if="isDispatch && control.add"
          @click="deploy('deploy','审批配置')"
        >配置</Button
        >
        </Col>
      </Row>
      <Row style="margin-top:20px;">
        <Col span="8" v-show="personType == 1">
        <Select
          v-model="searchParams.enterpriseId"
          style="width: 90%;"
          ref="treeSelectPro"
          placeholder="机构"
        >
          <Option
            v-for="item in list"
            :value="item.orgId"
            :key="item.orgId"
            style="display: none;"
          >{{ item.title }}</Option
          >
          <Tree
            :data="orgList"
            @on-select-change="checkOrg"
          ></Tree>
        </Select>
        </Col>
        <Col span="8">
        <Select
          v-model="searchParams.projectId"
          placeholder="项目"
          :clearable="proList.length>0 && personType !=3"
          style="width: 90%;"
        >
          <Option
            v-for="item in proList"
            :value="item.id"
            :key="item.id"
          >{{ item.shortName }}</Option
          >
        </Select>
        </Col>
        <Col span="8">
        <Input
          v-model="searchParams.constructionPointName"
          placeholder="工点"
          maxlength="50"
          style="width: 90%;"
        />
        </Col>
        </Row>
        <Row style="margin-top:20px;">
        <Col span="8">
          <Select
            v-model="searchParams.riskCategoryId"
            style="width: 90%;"
            clearable
            placeholder="请选择作业风险类别">
            <Option
              v-for="item in typelist"
              :value="item.id"
              :key="item.id"
            >{{ item.riskCategoryName }}</Option>
          </Select>
        </Col>
        <Col span="8" v-show="personType == 3">
          <Select
            v-model="searchParams.riskLevel"
            style="width: 90%;"
            clearable
            placeholder="请选择作业风险等级">
            <Option
              v-for="item in riskLevelList"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </Col>
        <Col span="8">
          <Select
            v-model="searchParams.stage"
            style="width: 90%;"
            clearable
            placeholder="状态">
            <Option
              v-for="item in statusList"
              :value="item.id"
              :key="item.id"
            >{{ item.name }}</Option>
          </Select>
        </Col>
      </Row>
      <Row style="margin-top:20px;">
        <Col span="24" style="text-align: right">
        <Button
          type="primary"
          style="margin-right: 15px"
          @click="searchList"
          v-if=" control.search"
        >搜索</Button>
        </Col>
      </Row>
    </div>
    <Tabs value="1" v-model="active" v-show="personType !=3" @on-click="activeTab" >
      <TabPane :label="label11"  name="1"></TabPane>
      <TabPane :label="label12"  name="2"></TabPane>
      <TabPane :label="label13"  name="3"></TabPane>
      <TabPane :label="label14"  name="4"></TabPane>
    </Tabs>
    <Table
      border
      :columns="columns"
      :data="measuresList"
      class="scroll-bar"
      @on-selection-change="selectChange"
    >
      <template slot-scope="{ row }" slot="step">
          <span :class="{
              'step--blue': 1 === row.step,
              'step--orange': 2 === row.step || 3 === row.step || 4 === row.step,
              'step--red': 5 === row.step,
              'step--green': 6 === row.step}">
            {{ row.stageName }}
          </span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <span title="方案制定" class="button-class" v-if="row.stage ==5 && control.editMeasure && personType == 3 && isDispatch" @click="makeMeasure('makeMeasure',row.id,row.riskLevel, '方案制定')" type="text">方案制定</span>
        <span title="方案修订" class="button-class" v-if="isDispatch && row.stage ==6 && control.editMeasure && personType ==3" @click="makeMeasure('editMeasure',row.id,row.riskLevel,'方案详情')" type="text">方案修订</span>
        <span title="撤销" class="button-class" v-if="isDispatch && row.stage == 7 && control.cancel && personType == 3" @click="revokeBtn(row.id)" type="text">撤销</span>
        <span title="审核" class="button-class" v-if="row.approval && control.examine" @click="detailBtn('examine',row.stage,row.id, '审核')" type="text">审核</span>
        <span title="签发" class="button-class" v-if="row.sign && control.Issue" @click="detailBtn('issue',row.stage, row.id, '签发')" type="text">签发</span>
        <span title="详情" class="button-class" v-if="control.detail" @click="detailBtn('details',row.stage, row.id, '方案详情')" type="text">详情</span>
      </template>
    </Table>
    <Row type="flex" justify="center">
      <Col>
      <Page
        class="pagination"
        :total="page.total"
        :current="page.current"
        :page-size="page.pageSize"
        :page-size-opts="[10,20,50,100]"
        @on-change="pageChange"
        @on-page-size-change="sizeChange"
        show-elevator
        show-total
        show-sizer
      />
      </Col>
    </Row>
     <Modal v-model="isInquiries" title="业务问询" width="50%" ok-text="提交" :footer-hide="true">
      <div class="modal-content">
        <inquiries ref="isInquiriesBox" :checkedRows="checkedRows" :businessType="businessType" @modelBox="modelBox" @person="person"></inquiries>
      </div>
    </Modal>
    <Modal v-model="personModel" title="选择人" width="80%" ok-text="提交" :footer-hide="true">
      <div class="modal-content">
        <checkPerson @personBox="personBox"></checkPerson>
      </div>
    </Modal>
    <span class="inquiries" @click="replyChild()">问询</span>
  </div>
</template>
<script>
import inquiries from '../../components/modules/inquiries/index'
import checkPerson from '../../components/modules/inquiries/checkPerson'
  import tree from 'vue-giant-tree'
  export default {
    name: 'management-and-measures',
    components: {
      tree,
      inquiries,
      checkPerson
    },
    data() {
      return {
        businessType:'businesstype_measures',
        isInquiries:false,
        personModel:false,
        searchParams: {}, //搜索条件
        isPerson:false,
        orgList: [], //机构树
        proList: [], //项目部树
        measuresList: [], //风险列表
        personDetail: {}, //人员信息
        list: [], //机构SELECT选择
        list1: [], //专业类型SELECT选择
        wbsList: [], //专业类型
        personStatusList: [],
        personType:'',
        active:'1',
        isDispatch:false,//是否是调度员
        showTree: false,
        page: {
          total: 0,
          current: 1,
          pageSize: 10,
          totalPage: 0
        },
        label11: h => {
          return h('div', [
            h(
              'span',
              {
                style: {
                  color: '#EF3E43'
                }
              },
              'Ⅰ级风险'
            )
          ])
        },
        label12: h => {
          return h(
            'span',
            {
              style: {
                color: '#F86A30'
              }
            },
            'Ⅱ级风险'
          )
        },
        label13: h => {
          return h(
            'span',
            {
              style: {
                color: '#F3CF34'
              }
            },
            'Ⅲ级风险'
          )
        },
        label14: h => {
          return h(
            'span',
            {
              style: {
                color: '#3D6FC9'
              }
            },
            'Ⅳ级风险'
          )
        },
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '序号',
            align: 'center',
            width: 70,
            render: (h, params) => {
              return h('span', params.index + (this.page.current - 1) * this.page.pageSize + 1)
            }
          },
          {
            title: '公司名称',
            key: 'enterpriseName',
            align: 'center',
            tooltip:true,
            checkAccess:[1],
          },
          {
            title: '项目名称',
            key: 'projectName',
            align: 'center',
            tooltip:true,
            checkAccess:[1,2],
          },
          {
            title: '工点名称',
            key: 'constructionPointName',
            tooltip:true,
            align: 'center'
          },
          {
            title: '是否在施',
            key: 'isWork',
            align: 'center',
            width:'70',
          },
          {
            title: '作业风险类型',
            align: 'center',
            tooltip:true,
            key: 'riskCategoryNames'
          },
          {
            title: '作业风险名称',
            align: 'center',
            tooltip:true,
            key: 'riskName'
          },
          {
            title: '作业风险等级',
            align: 'center',
            key: 'riskLevelName',
            checkAccess:[3],
          },
          {
            title: '状态',
            key: 'stageName',
            align: 'center',
            slot: 'step'
          },
          {
            title: '操作',
            align: 'center',
            slot: 'action',
            width:'150',
          }
        ],
        listParam: {
          name: ''
        },
        page: {
          total: 0,
          current: 1,
          pageSize: 10,
          totalPage: 0
        },
        dictList:[],
        typelist:[],
        control:{},
        projectList:[],
        treeList:[],
        riskLevelList: [
          { id: '1', name: 'Ⅰ级' },
          { id: '2', name: 'Ⅱ级' },
          { id: '3', name: 'Ⅲ级' },
          { id: '4', name: 'Ⅳ级' }
        ],

        statusList: [
          { id: '1', name: '待确认' },
          { id: '2', name: '项目待审' },
          { id: '3', name: '公司待审' },
          { id: '4', name: '集团待审' },
          { id: '5', name: '审核驳回' },
          { id: '6', name: '已通过' },
        ],
        checkedRows:[]
      }
    },
    methods: {
      selectChange(selection) {
        this.checkedRows = selection
      },
      // 打开问询弹框
      replyChild(){
        if(this.checkedRows.length > 5){
          this.$Message.warning('最多可选5条风险进行批量问询')
          return 
        }else if(this.checkedRows.length == 0){
            this.$Message.warning('请先选择需要问询的风险')
            return
        }else{
            let isM = true,self = this
            try{
                self.checkedRows.forEach((e,index)=>{
                    if(index>0){
                        if(e.projectId != self.checkedRows[index-1].projectId){
                            this.$Message.warning('仅能选择同一项目下的风险询问')
                            isM = false
                            throw Error()
                        }
                    }
                })
            }catch(e){}
            if(isM){
                this.isInquiries = true
                this.$refs.isInquiriesBox.isModel()
            }
        }
      },
      // 关闭问询框
      modelBox(){
        this.isInquiries = false
      },
      // 打开人员选择框
      person(){
        this.personModel = true
      },
      // 关闭人员选择框
      personBox(){
        this.personModel = false
      },
      //跳转详情
      detailBtn(type,status,id, name) {
        if(type == 'examine'){
          this.$router.push({
            name: `management-and-measures-examine`,
            params:{
              type:type,
              id:id,
              status:status,
              name:name
            }
          })
        }else{
          this.$router.push({
            name: `management-and-measures-issue`,
            params:{
              type:type,
              id:id,
              status:status,
              name:name
            }
          })

        }

      },
      //方案制定
      makeMeasure(type, id,level,name) {
        if(type == 'makeMeasure'){
          this.$router.push({
            name: `make-measures-add`,
            params:{
              type:type,
              id:id,
              level:level,
              name:name
            }
          })
        }else{
          this.$router.push({
            name: `make-measures-edit`,
            params:{
              type:type,
              id:id,
              level:level,
              name:name
            }
          })
        }

      },
      //按钮权限
      buttonShow() {
        let buttonList = JSON.parse(localStorage.getItem('buttonList'))
        buttonList.map(val => {
          let key = Object.keys(val).toString()
          if (key === this.$route.name) {
            Object.values(val)[0].map(item => {
              if (item.code == 'P_0801_01') {
                this.control.add = true
              } else if (item.code == 'P_0801_02') {
                this.control.search = true
              } else if (item.code == 'P_0801_03') {
                this.control.makeMeasure = true
              } else if (item.code == 'P_0801_04') {
                this.control.cancel = true
              } else if (item.code == 'P_0801_05') {
                this.control.examine = true
              } else if (item.code == 'P_0801_06') {
                this.control.Issue = true
              } else if (item.code == 'P_0801_07') {
                this.control.editMeasure = true
              } else if (item.code == 'P_0801_08') {
                this.control.detail = true
              }
            })
          }
        })
      },
      deploy(type,name){
        this.$router.push({
          path: `deploy-person/${type}/${name}`,
        })
      },
      //查询用户权限
      getUserDetail() {
        localStorage.setItem('userDetail','');
        this.$api.projectInquiry.getUserDetail().then(res => {
          if (res.code == 200) {
            this.personDetail = res.data;
            if (res.data.userInOrgType == 'PROJECT_TEAM_USER') {
              this.personType = 3;
              this.searchParams.riskLevel = '';
              this.getProList({objectId:this.personDetail.projectTeamId});

            }else if(res.data.userInOrgType == 'ROOT_ENTERPRISE_USER'){
              this.personType = 1;
              this.getOrgTree()
            }else if(res.data.userInOrgType == 'NOMAL_ENTERPRISE_USER'){
              this.personType = 2;
              this.getProList({objectId:this.personDetail.enterpriseId});
            }

            localStorage.setItem('userDetail',JSON.stringify(this.personDetail))
            this.checkPerson(this.personDetail);
            this.handleColumns(this.columns);
          } else {
            this.$Message.error(res.data.msg)
          }
        })
      },
      //查询当前用户是否为调度员
      checkPerson(){
        this.$api.measurePlan.checkDispatch().then(res => {
          if (res.code == 200) {
            this.isDispatch = true
          } else {
            this.isDispatch = false
          }
        })
      },
      //风险类别
      getRiskCategoryFindAll() {
        this.$api.measuresLibrary.getRiskCategoryFindAll().then(res => {
          if (res.code == 200) {
            res.data.forEach(item=>{
              this.typelist.push(item)
            })
          } else {
            this.$Message.error(res.message)
          }
        })
      },
      activeTab(code){
        this.page = {
          total: 0,
            current: 1,
            pageSize: 10,
            totalPage: 0
        }
        this.active = code;
        this.getRiskList();
      },
      revokeBtn(id){//撤销
        this.$Modal.confirm({
          title: '温馨提示',
          closable: true,
          content: '确认要撤销吗？',
          width: 360,
          onOk: () => {
            this.getRiskOrderDestroyoperate(id)
          }
        })
      },
      getRiskOrderDestroyoperate(id){
        this.$api.measurePlan.revoke(id).then(res => {
          if(res.code === 200){
            this.$Message.success(res.message);
            this.getRiskList()
          }else {
            this.$Message.warning(res.message)
          }
        })
      },
      //获取机构树
      getOrgTree() {
        this.orgList = [];
        this.list = [];
        this.$api.measurePlan.getOrgTree().then((res) => {
          if (res.code == 200) {
            this.orgList = res.data
            let orgId = this.orgList[0].objectId
            let title = this.orgList[0].title
            this.list = []
            this.list.push({
              orgId,
              title
            })
            this.getProList(this.orgList[0]);
            this.searchParams.enterpriseId = orgId;

          } else {
            this.$Message.error(res.data.msg);
          }
        })
      },
      checkOrg(data) {
        if (data.length > 0) {
          this.list = []
          let orgId = data[0].objectId
          let title = data[0].title
          this.list.push({
            orgId,
            title
          })
          this.getProList(data[0]);
          this.searchParams.enterpriseId = orgId
          this.$refs.treeSelectPro.visible = false
        }
      },
      //获取项目列表
      getProList(data) {
        this.proList = [];
        if(data.type == 2){
          this.proList.push({
            shortName:data.linkedShortName,
            id:data.linkedId,
          })
        }else{
          this.$api.measurePlan.getProList(data.objectId).then(res => {
            if (res.code === 200) {
              if(res.data.length>0){
                res.data.forEach(item=>{
                  this.proList.push(item);
                })

                if(this.personType == 3){
                  this.searchParams.projectId = this.proList[0].id;
                }else{
                  this.searchParams.projectId = -1;
                }
                this.getRiskList();
              }
            } else {
              this.$Message.error(res.message)
            }
          })
        }

      },
      searchList(){
        this.page.current = 1;
        this.page.pageSize = 10;
        this.getRiskList();
      },
      //获取项目列表
      getRiskList() {
        let data = {
          pageSize: this.page.pageSize,
          currentPage: this.page.current,
          whereMap: this.searchParams
        }
        if(!data.whereMap.enterpriseId){
          data.whereMap.enterpriseId = this.personDetail.enterpriseId;
        }
        if(this.personType != 3){
          data.whereMap.riskLevel = this.active;
        }
        if(!this.searchParams.projectId){
          data.whereMap.projectId = -1
        }
        this.$api.measurePlan.getRiskList(data).then(res => {
          if (res.code == 200) {
            if (res.data.resultObject) {
              this.measuresList = res.data.resultObject
              this.page.total = res.data.totalRecord
              this.page.totalPage = res.data.totalPages
            }
          } else {
            this.$Message.error(res.message)
          }
        })
      },

      pageChange(current) {
        this.page.current = current
        this.getRiskList()
      },
      sizeChange(size) {
        this.page.pageSize = size
        this.getRiskList()
      },
      //表格权限展示
      handleColumns (columns) {
        // 遍历处理列数组list，判断查询是否是权限选择列，如果是权限列，判断角色是否有权限，有则显示，无则隐藏
        columns.map((item, index) => {
          let checkAccess = item.checkAccess
          let access = this.personType
          if(checkAccess){
            // 判断角色是否有权限，checkAccess是列传过来的值，access是用户登录时后台返回值
            if (this.isInArray(checkAccess,access)) {

            } else {
              this.columns.splice(index, 1)
              this.handleColumns(this.columns)
            }
          }
        })
      },
      isInArray(arr,value){
        for(var i = 0; i < arr.length; i++){
          if(value === arr[i]){
            return true;
          }
        }
        return false;
      }
    },

    mounted() {
      this.buttonShow();
      this.getUserDetail()
      this.getRiskCategoryFindAll();
    },
    activated(){
      this.page = {
        total: 0,
        current: 1,
        pageSize: 10,
        totalPage: 0
      },
      this.getRiskList()
    }
  }
</script>
<style>
  .tree {
    width: 250px;
    margin-left: 50px;
    overflow: auto;
    height: 200px;
  }
  .search-title {
    width: 100%;
    height: 40px;
    line-height: 40px;
    display: block;
  }
  .step--blue {
    color: #3170C8;
  }

  .step--orange {
    color: #E7AF63;
  }
  .step--red {
    color: #EE4044;
  }
  .step--green {
    color: #3BBB0A;
  }
</style>
